package com.gxa.autoparts.core.interceptor;

import com.gxa.autoparts.core.common.ExceptionCode;
import com.gxa.autoparts.core.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author HS
 */
@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    HttpServletRequest request;

    /**
     * 在方法执行前执行的操作
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String remoteAddr = request.getRemoteAddr();

        String token = request.getHeader("token");
        System.out.println("前端token："+token);
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(remoteAddr);
        System.out.println("后端的token："+attribute);
        if (attribute == null){
            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
        }
        String sessionToken = attribute.toString();

        if (sessionToken != null && sessionToken.equals(token)) {
            return true;
        }else {
            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
        }
//        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在方法执行后执行的操作(指放行后)
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
